﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HealthHelper
{
    public partial class FrmMain : FrameForm
    {
        public FrmMain()
        {
            InitializeComponent();
        }
        ConfigJson configJson = null;

        private void FrmMain_Load(object sender, EventArgs e)
        {
            configJson = ConfigJsonFactory.LoadConfig();
            txt_Time.Text = configJson.WorkMinutes.ToString();
            btn_Switch.Checked = configJson.RestOpen;
            txt_Time.MinValue = uc_Meter.MinValue = configJson.MinWorkMinutes;
            txt_Time.MaxValue = uc_Meter.MaxValue = configJson.MaxWorkMinutes;
            new Thread(WorkThrd).Start();
        }

        AutoResetEvent waitEvent = new AutoResetEvent(false);

        private bool appRun = true;

        // 工作时长
        protected int WorkSecond
        {
            get
            {
                return configJson.WorkMinutes * 60;
            }
        }

        // 休息时长
        protected int RestSecond
        {
            get
            {
                return configJson.RestMinutes * 60;
            }
        }

        // 休息提醒秒
        protected int RestRemindSecond
        {
            get
            {
                return configJson.RestRemindSecond > 0 ? configJson.RestRemindSecond : 3;
            }
        }

        // 开启休息标识
        protected bool RestOpen
        {
            get
            {
                return configJson.RestOpen;
            }
        }

        /// <summary>
        /// 当前状态
        /// </summary>
        protected StateEnum curState = StateEnum.WORK;

        /// <summary>
        /// 工作线程
        /// </summary>
        private void WorkThrd()
        {
            while (appRun)
            {

                if (!RestOpen)
                    goto nextWait;
                switch (curState)
                {
                    case StateEnum.WORK: // 工作中
                        Working();
                        break;
                    case StateEnum.REST: // 休息中
                        Resting();
                        break;
                }
            nextWait:
                // 以500ms为单位定时
                waitEvent.WaitOne(300);
            }
        }

        // 最后一次记录的时间
        private DateTime lastRecordTime = DateTime.Now;

        // 休息等待时间
        private int RsetWaitSeconds = 0;

        /// <summary>
        /// 工作中
        /// </summary>
        private void Working()
        {
            double totalSeconds = (DateTime.Now - lastRecordTime).TotalSeconds;
            // 间隔时间小于设置的工作时间直接返回
            if (totalSeconds < WorkSecond)
            {
                RsetWaitSeconds = WorkSecond - (int)totalSeconds;
                if (RsetWaitSeconds <= RestRemindSecond)
                    StartCountdown();
                RefreshCountdownTime(RsetWaitSeconds);
                Console.WriteLine("工作中：" + DateTime.Now);
                return;
            }
            // 开始休息
            StartRest();
        }

        FrmNotice frmNotice = null;
        /// <summary>
        /// 开始倒计时
        /// </summary>
        private void StartCountdown()
        {
            if (frmNotice != null && !frmNotice.IsDisposed)
                return;
            Task.Factory.StartNew(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    frmNotice = new FrmNotice();
                    frmNotice.NoticeOperEvent += (operId) =>
                    {

                        switch (operId)
                        {
                            case 0:     // 0：设置
                                this.Show();
                                break;
                            case 1:     // 1：暂不休息
                                StartWork();    // 不休息就开始工作
                                break;
                            case 2:     // 2：立即休息
                                StartRest();
                                break;
                            default:
                                break;
                        };
                    };
                    frmNotice.GetRsetWaitSecondsEvent += () => { return RsetWaitSeconds; };
                    frmNotice.Show();
                }));
            });

        }

        // 刷新倒计时时间
        private void RefreshCountdownTime(int rsetWaitSeconds)
        {
            var seconds = (int)(rsetWaitSeconds % 60);
            var minutes = (int)(rsetWaitSeconds / 60) % 60;
            var hours = (int)(rsetWaitSeconds / 3600) % 60;
            DateTime newTime = DateTime.Today.AddHours(hours).AddMinutes(minutes).AddSeconds(seconds);
            if (ut_RestCountDown.Value != newTime)
            {
                if (!this.ut_RestCountDown.IsDisposed)
                    this.ut_RestCountDown.Invoke(new Action(() => { ut_RestCountDown.Value = newTime; }));
            }

        }


        /// <summary>
        /// 开始休息
        /// </summary>
        private void StartRest()
        {
            // 开始休息设置等待时间为0
            RsetWaitSeconds = 0;
            Console.WriteLine("开始休息：" + DateTime.Now);
            lastRecordTime = DateTime.Now;
            curState = StateEnum.REST;
        }

        FrmRest frmRest = null;

        /// <summary>
        /// 休息中
        /// </summary>
        private void Resting()
        {
            double totalSeconds = (DateTime.Now - lastRecordTime).TotalSeconds;
            // 休息的间隔时间小于设置的休息间隔直接返回
            if (totalSeconds < RestSecond)
            {
                Console.WriteLine("休息中：" + DateTime.Now);

                if (frmRest == null)
                {
                    this.Invoke(new Action(() =>
                    {
                        frmRest = new FrmRest();
                        frmRest.Show();
                        frmRest.FormClosed += (sendr, e) =>
                        {
                            frmRest = null;
                            StartWork();
                            return;
                        };
                    }));
                }
                int countDownSecond = RestSecond - (int)totalSeconds;
                frmRest.RefreshRestTime(countDownSecond + "S", (int)totalSeconds * 100 / RestSecond);
                return;
            }
            // 开始工作
            StartWork();
        }

        /// <summary>
        /// 开始工作
        /// </summary>
        private void StartWork()
        {
            if (frmRest != null)
            {
                this.Invoke(new Action(() => { frmRest.Close(); }));
                frmRest = null;
            }
            Console.WriteLine("开始工作：" + DateTime.Now);
            lastRecordTime = DateTime.Now;
            curState = StateEnum.WORK;
        }


        //***********************下面控件操作***********************//

        private void btn_Switch_CheckedChanged(object sender, EventArgs e)
        {
            uc_Meter.Enabled = btn_Switch.Checked;
            lb_Time.ForeColor = btn_Switch.Checked ? SystemColors.MenuHighlight : Color.Silver;
            if (btn_Switch.Checked)
                StartWork();
            else
                ut_RestCountDown.Value = DateTime.Today;
            // 设置开关
            if (configJson.RestOpen != btn_Switch.Checked)
            {
                configJson.RestOpen = btn_Switch.Checked;
                ConfigJsonFactory.WriteConfig(configJson);
            }
        }

        private void btn_Modify_Click(object sender, EventArgs e)
        {
            txt_Time.ReadOnly = false;
            txt_Time.Visible = true;
            lb_Time.Visible = !txt_Time.Visible;
            txt_Time.Focus();
        }

        private void txt_Time_Leave(object sender, EventArgs e)
        {
            ModifyOver();
            Console.WriteLine("leave");
        }

        private void ModifyOver()
        {
            txt_Time.ReadOnly = true;
            txt_Time.Visible = false;
            lb_Time.Visible = !txt_Time.Visible;
            int.TryParse(txt_Time.Text, out int num);
            if (num < txt_Time.MinValue)
                txt_Time.Text = txt_Time.MinValue.ToString();
            if (configJson.WorkMinutes != num)
            {
                configJson.WorkMinutes = num;
                ConfigJsonFactory.WriteConfig(configJson);
            }
        }

        private void txt_Time_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键  
            {
                if (e.KeyChar == (char)13)//回车
                {
                    e.Handled = true;
                    ModifyOver();
                    return;
                }
                if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字  
                {
                    e.Handled = true;
                    return;
                }
            }
        }

        private void txt_Time_TextChanged(object sender, EventArgs e)
        {
            int.TryParse(txt_Time.Text, out int num);
            if (num > txt_Time.MaxValue)
                txt_Time.Text = txt_Time.MaxValue.ToString();
            uc_Meter.Value = num;
            lb_Time.Text = txt_Time.Text;
        }

        private void pb_Close_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            appRun = false;
            waitEvent.Set();
            Application.ExitThread();
            Application.Exit();
        }

        private void FrmMain_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();//可以要，也可以不要，取决于是否隐藏主窗体
                this.notifyIcon.Visible = true;
            }
        }

        private void 设置ToolStripMenuItem_MouseDown(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }
        private void 退出ToolStripMenuItem_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Close();
            }
        }
        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void notifyIcon_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.contextMenuStrip.Show(MousePosition.X, MousePosition.Y - this.contextMenuStrip.Height / 2);
            }
        }
    }
}
